$(function () {
    query();
    $(".js-back-btn").unbind("click").click(function () {
        $("#itemdiv").hide();
        $("#itemlistdiv").show();
    })
    $(".js-child-item").unbind("click").click(function () {
        addChildItem();
    })
    getVoteInfo();
})

function query() {
    $("#myTable").bootstrapTable({
        url: '/ret/oaget/getVoteItemListForManage?voteId=' + voteId,
        method: 'post',
        contentType: 'application/x-www-form-urlencoded',
        toolbar: '#toobar',//工具列
        striped: true,//隔行换色
        cache: false,//禁用缓存
        pagination: true,//启动分页
        sidePagination: 'server',//分页方式
        pageNumber: 1,//初始化table时显示的页码
        pageSize: 10,//每页条目
        showFooter: false,//是否显示列脚
        showPaginationSwitch: false,//是否显示 数据条数选择框
        sortable: true,//排序
        sortOrder: "ASC",
        search: false,//启用搜索
        showColumns: false,//是否显示 内容列下拉框
        showRefresh: false,//显示刷新按钮
        idField: 'recordId',//key值栏位
        clickToSelect: true,//点击选中checkbox
        pageList: [10, 20, 30, 50],//可选择单页记录数
        queryParams: queryParams,
        columns: [{
            checkbox: true
        }, {
            field: 'num',
            title: '序号',//标题  可不加
            width: '50px',
            formatter: function (value, row, index) {
                return index + 1;
            }
        }, {
            field: 'voteTitle',
            title: '投票标题',
            width: '150px',
            formatter:function (value,row,index)
            {
                return "<a href=\"javascript:void(0);details('" + row.recordId + "')\" style='cursor: pointer'>"+value+"</a>";
            }
        }, {
            field: 'title',
            title: '投票项标题',
            width: '150px'
        }, {
            field: 'optType',
            title: '投票方式',
            width: '50px',
            formatter: function (value, row, index) {
                if (value == "1") {
                    return "单选";
                } else if (value == "2") {
                    return "多选";
                } else if (value == "3") {
                    return "简述";
                }
            }
        }, {
            field: 'createTime',
            width: '100px',
            title: '创建时间'
        }, {
            field: 'createUser',
            width: '50px',
            title: '创建人',
            formatter: function (value, row, index) {
                return getUserNameByStr(value);
            }
        }, {
            field: 'opt',
            title: '操作',
            align: 'center',
            width: '180px',
            formatter: function (value, row, index) {
                return createOptBtn(row.recordId);
            }
        }],
        onClickCell: function (field, value, row, $element) {
            //alert(row.SystemDesc);
        },
        responseHandler: function (res) {
            if (res.status == "500") {
                console.log(res.msg);
            } else if (res.status == "100") {
                layer.msg(sysmsg[res.msg]);
            } else {
                return {
                    total: res.list.total, //总页数,前面的key必须为"total"
                    rows: res.list.list
                    //行数据，前面的key要与之前设置的dataField的值一致.
                };
            }
        }
    });
}

function queryParams(params) {
    var temp = {
        search: params.search,
        pageSize: this.pageSize,
        pageNumber: this.pageNumber,
        sort: params.sort,
        sortOrder: params.order
    };
    return temp;
};

function createOptBtn(recordId) {
    var html = "<a href=\"javascript:void(0);edit('" + recordId + "')\" class=\"btn btn-success btn-xs\" >编辑</a>&nbsp;&nbsp;" +
        "<a href=\"javascript:void(0);del('" + recordId+ "')\" class=\"btn btn-darkorange btn-xs\" >删除</a>";
    return html;
}

function addChildItem() {
    var index = $("#child-item-table").find("tr").length;
    $("#child-item-table").append("<tr><td><input type='number' name='sortNo' value='" + index + "' class='form-control'></td><td><input type='text' name='childTitle' class='form-control'></td>" +
        "<td><input type='text' name='childRemark' class='form-control'></td><td><a onclick=\"deleteChildItem(this)\" class='btn btn-darkorange btn-xs'>删除</a></td></tr>");
}

function createChildItem(childItemArr) {
    $("#child-item-table").find("tr").next().remove();
    for (var i = 0; i < childItemArr.length; i++) {
        $("#child-item-table").append("<tr><td><input type='number' name='sortNo' value='" + (i + 1) + "' class='form-control' data-value='" + childItemArr[i].recordId + "'></td>" +
            "<td><input type='text' name='childTitle' class='form-control' value='" + childItemArr[i].childTitle + "'></td>" +
            "<td><input type='text' name='childRemark' class='form-control' value='" + childItemArr[i].childRemark + "'></td><td><a onclick=\"deleteChildItem(this)\" class='btn btn-darkorange btn-xs'>删除</a></td></tr>");

    }
}

function edit(recordId) {
    var flag = $("#optType").val();
    $("#itemlistdiv").hide();
    $("#itemdiv").show();
    $.ajax({
        url: "/ret/oaget/getVoteItemById",
        type: "post",
        dataType: "json",
        data: {recordId: recordId, levelId: "0"},
        success: function (data) {
            if (data.status == "200") {
                var itemInfo = data.list;
                for (var id in itemInfo) {
                    if (id == "childItem") {
                        var childItemArr = JSON.parse(itemInfo[id]);
                        createChildItem(childItemArr);
                    } else {
                        $("#" + id).val(itemInfo[id]);
                    }
                }
                $(".js-update-save").unbind("click").click(function () {
                    updateVoteItem(recordId);
                })
            } else if (data.status == "100") {
                layer.msg(sysmsg[data.msg]);
            } else if (data.status == "500") {
                console.log(data.msg);
            }
        }
    })

}

function del(recordId) {
    if (confirm("确定删除当前投票项吗？")) {
        $.ajax({
            url: "/set/oaset/deleteVoteItems",
            type: "post",
            dataType: "json",
            data: {
                voteId: voteId,
                recordId: recordId
            },
            success: function (data) {
                if (data.status == "500") {
                    console.log(data.msg);
                } else if (data.status == "100") {
                    layer.msg(sysmsg[data.msg]);
                } else {
                    layer.msg(sysmsg[data.msg]);
                    $("#myTable").bootstrapTable('refresh');
                }
            }
        });
    }
}

function details(recordId) {
    window.open("/app/core/vote/sendvote?view=itemdetails&recordId=" + recordId);
}

function deleteChildItem(Obj) {
    $(Obj).parent("td").parent("tr").remove();
}

function getVoteInfo() {
    $.ajax({
        url: "/ret/oaget/getVoteById",
        type: "post",
        dataType: "json",
        data: {
            voteId: voteId
        },
        success: function (data) {
            if (data.status == "200") {
                $("#voteTitle").html(data.list.title);
            } else if (data.status == "100") {
                layer.msg(sysmsg[data.msg]);
            } else if (data.status == "500") {
                console.log(data.msg);
            }
        }
    })
}

function updateVoteItem(recordId) {
    $.ajax({
        url: "/set/oaset/updateVoteItems",
        type: "post",
        dataType: "json",
        data: {
            voteId: voteId,
            recordId: recordId,
            sortNo: $("#sortNo").val(),
            title: $("#title").val(),
            optType: $("#optType").val(),
            remark: $("#remark").val(),
            childItem: getParam(recordId)
        },
        success: function (data) {
            if (data.status == "500") {
                console.log(data.msg);
            } else if (data.status == "100") {
                layer.msg(sysmsg[data.msg]);
            } else {
                window.location.reload();
                layer.msg(sysmsg[data.msg]);
            }
        }
    })
}


function getParam(recordId) {
    var paramArr = [];
    $("#child-item-table").find("tr").next().each(function () {
        var json = {};
        var recordId = $(this).children("td").eq(0).find("input").attr("data-value")
        var sortNo = $(this).children("td").eq(0).find("input").val();
        var childTitle = $(this).children("td").eq(1).find("input").val();
        var childRemark = $(this).children("td").eq(2).find("input").val();
        json.recordId = recordId;
        json.sortNo = sortNo;
        json.childTitle = childTitle;
        json.childRemark = childRemark;
        paramArr.push(json);
    });
    return JSON.stringify(paramArr);
}
